import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userApi } from '@/api/train'
import type { User, LoginRequest } from '@/types/train'

export const useUserStore = defineStore('user', () => {
  const currentUser = ref<User | null>(null)
  const isLoggedIn = ref(false)

  // 登录
  const login = async (loginData: LoginRequest) => {
    const response = await userApi.login(loginData)
    if (response.success) {
      currentUser.value = response.data
      isLoggedIn.value = true
      // 保存到localStorage
      localStorage.setItem('currentUser', JSON.stringify(response.data))
      console.log('登录成功', response.data)
      return response
    }
    return response
  }

  // 登出
  const logout = () => {
    currentUser.value = null
    isLoggedIn.value = false
    localStorage.removeItem('currentUser')
  }

  // 从localStorage恢复用户状态
  const restoreUser = () => {
    const userStr = localStorage.getItem('currentUser')
    if (userStr) {
      try {
        currentUser.value = JSON.parse(userStr)
        isLoggedIn.value = true
      } catch {
        localStorage.removeItem('currentUser')
      }
    }
  }

  // 检查是否为管理员
  const isAdmin = () => {
    return currentUser.value?.role === 'ADMIN'
  }

  return {
    currentUser,
    isLoggedIn,
    login,
    logout,
    restoreUser,
    isAdmin
  }
})
